<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=0.5"/>
    <title>流程添加</title>
    <script src="/static/bflow/assets/js/scriptLib.js"></script>
    <!-- bootstrap-validator -->
    <script src="https://cdn.bootcss.com/1000hz-bootstrap-validator/0.11.9/validator.min.js"></script>
    <link rel="stylesheet" href="/static/bflow/assets/components/introjs/introjs.css" />

</head>
<body>
<div class="container">
    <div class="page-header">
        <h1><label id="pageTitle">流程添加</label>
            <small><a href="/static/bflow/ui/define/processList.html" class="btn btn-outline btn-default"><i class="glyphicon glyphicon-chevron-left"></i>返回列表</a></small>
        </h1>
    </div>
    <form id="inputForm" role="form" class="form-horizontal">
        <div class="col-md-12">
            <div class="form-group">
                <label class="col-sm-2 control-label">流程KEY：</label>
                <div class="col-sm-10">
                    <input type="text" name="key" pattern="^[_A-z]{1,}$" class="form-control" required>
                    <span class="help-block m-b-none">英文命名</span>
                </div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">流程名称：</label>
                <div class="col-sm-10">
                    <input type="text" name="name" class="form-control" required>
                </div>
            </div>
            <div class="form-group" data-step="1" data-intro="1、默认模式: 按活动先后顺序扭转 <br> 2、自定义模式: 选择活动后 排好序, 再设置条件分支(一经设置则不再允许排序)">
                <label class="col-sm-2 control-label">活动集合：</label>
                <div class="col-sm-5">
                    <input type="hidden" id="actSet" name="actSet" required>
                    <label class="radio-inline radio-inline-first">
                        <input type="radio" value="def" name="type" required>
                        <span class="radio-label" data-toggle="tooltip" data-html="true" title="依据排序扭转流程">默认</span>
                    </label>
                    <label class="radio-inline">
                        <input type="radio" value="set" name="type" required>
                        <span class="radio-label" data-toggle="tooltip" title="可设置条件分支">自定义</span>
                    </label>
                    <div class="sortable-list" style="margin-left: 0px;">
                        <ul id="actListUL" style="min-height: 40px;">
                        </ul>
                        <span class="help-block m-b-none">
                            <button type="button" class="btn btn-danger" onclick="chooseAct()" style="padding: 0;margin: 0;">＋选择</button>
                            提示: 第一个为启动节点, [活动ID]</span>
                    </div>
                </div>
                <div id="actRouteSet" class="col-sm-10 col-sm-offset-2"></div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">流程描述：</label>
                <div class="col-sm-10">
                    <textarea name="desc" rows="3" class="form-control" maxlength="120" data-count="true"></textarea>
                    <span class="word-num-tip help-block">0/100</span>
                </div>
            </div>
            <div class="form-group">
                <div class="col-sm-12 col-sm-offset-2">
                    <input name="id" type="hidden" />
                    <button class="btn btn-primary" type="submit">保存内容</button>
                    <button class="btn btn-default" type="reset">重置</button>
                </div>
            </div>
        </div>
    </form>
</div>
</body>

<!-- sortable -->
<link rel="stylesheet" href="/static/bflow/assets/components/sortable/sortable.css">
<script src="/static/bflow/assets/components/sortable/Sortable.min.js"></script>
<script src="/static/bflow/assets/components/introjs/intro.js"></script>
<script src="/static/bflow/assets/components/jquery/jquery.serializejson.min.js"></script>
<script type="text/javascript">
    var __routeMap = new Map();
    var __routeKeyPrefix = "route_";
    var actList = null;
    $(function () {
        initInputFormData();

        // 表单验证 http://1000hz.github.io/bootstrap-validator/
        $('#inputForm').validator().on('submit', function (e) {
            if (e.isDefaultPrevented()) {
                // handle the invalid form...
                log(__routeMap);
            } else {
                //防止重复提交
                FormUtil.blockRepeatSubmit($('#inputForm'), 2000);
                log(__routeMap);
                saveRouteMap(); //保存 上次编辑的规则
                log(__routeMap);
                var flag = setHiddenInputActSet();
                if(!flag){
                    return false;
                }

                var paramArr = $("#inputForm").serializeJSON();
                log(paramArr);
                if($("input[name=type]:checked").val()=="set"){
                    var vals = __routeMap.values();
                    if(vals.length == 0){
                        dialogTipError("请设置条件分支");
                        return false;
                    }
                    var routeDex = 0;
                    for(var i=0; i<vals.length; i++){
                        var group = JSON.parse(vals[i]);
                        log(group);
                        for(var g=0; g<group.length; g++){
                            var json = group[g];
                            log(json);
                            for(var key in json){
                                paramArr['routeBos['+routeDex+'].'+key] = json[key];
                            }
                            routeDex++;
                        }
                    }
                }
                HttpUtil.ajaxAsyncJsonPost("/bflow/defineProcess/save", paramArr, function(message){
                    dialogTipSuccess(message);
                    refreshPage(1500, '/static/bflow/ui/define/processList.html');
                });
                return false;
            }
        });


        setTimeout(function () {
            //初始化绑定
            bindActItemEdit();
        }, 500);
    });

    //活动集合插件
    var actListUL = document.getElementById("actListUL");
    actList = Sortable.create(actListUL, {
        group: "act",
        animation: 150,
        onAdd: function (evt){ console.log('onAdd.bar:', evt.item); },
        onUpdate: function (evt){
            console.log('onUpdate.bar:', evt.item);
        },
        onRemove: function (evt){ console.log('onRemove.bar:', evt.item); },
        onStart:function(evt){
            console.log(evt.oldIndex);
            console.log('onStart.foo:', evt.item);
        },
        onEnd: function(evt){
            console.log(evt.oldIndex, evt.newIndex);
            console.log('onEnd.foo:', evt.item);
        },
        filter: '.js-remove',
        onFilter: function (evt) {
            evt.item.parentNode.removeChild(evt.item);
        }
    });

    // 初始化表单数据
    function initInputFormData(){
        var id = getBrowserQueryVar("id");
        if(CommUtil.isNotEmpty(id)){
            HttpUtil.ajaxAsyncJsonPost("/bflow/defineProcess/get", {id: id}, function(data){
                console.log("data", data);
                var bo = data.bo;
                var routesGroup = data.routesGroup;
                FormUtil.bindFormData("inputForm", bo);
                loadActLi(bo.actSet, function(actIds){
                    //渲染 活动条件值
                    console.log("渲染条件值 ", actIds);
                    var groupKey, groupVals;
                    for(var i=0; i<actIds.length; i++){
                        actId = actIds[i];
                        groupKey = actId+"_"+i;
                        groupVals = routesGroup[groupKey];
                        log(groupVals);
                        __routeMap.put(__routeKeyPrefix+i, JSON.stringify(groupVals));
                    }
                    log(__routeMap);
                });
            });
        }
    }

    //绑定活动编辑
    var __lastIndex = -1;
    function bindActItemEdit(){
        $("#actListUL li").on("click", function (e) {
            var type = $("input[name=type]:checked").val();
            if(type=="set"){
                var jsonArr = saveRouteMap(); //保存 上次编辑的规则
                if(jsonArr.length > 0)
                    actList.options.disabled = true; //设置 后就不允许拖动了

                var item = $(e.currentTarget).find("label");
                item.closest("li").addClass("active").siblings().removeClass("active");
                var id = item.data("id");
                var dex = item.closest("li").index();
                __lastIndex = dex;
                var cacheVal = __routeMap.get(__routeKeyPrefix+dex);
                log("解析:"+cacheVal);
                $("#actRouteSet").html('');
                if(CommUtil.isNotEmpty(cacheVal)){
                    var jsonArr = JSON.parse(cacheVal);
                    log(jsonArr);
                    var obj = null;
                    for(var i=0; i<jsonArr.length; i++){
                        obj = jsonArr[i];
//                        log(obj);
                        var str = buildRouteItem(id, dex, i>0, obj);
                        $("#actRouteSet").append(str);
                    }
                }else{
                    var str = buildRouteItem(id, dex);
                    $("#actRouteSet").html(str);
                }
                $("#actRouteSet").append('<div id="addBtn" class="form-group"><a href="javascript:addRouteItem(\''+id+'\', '+dex+')" class="pull-right mgr-12">添加</a></div>');
            }else{
                $("#actRouteSet").html("<p class='text-warning' style='line-height: 50px'>默认按顺序扭转</p>");
            }
        });
    }

    //保存 上次编辑的规则
    function saveRouteMap(){
        var jsonArr = [];
        if(__lastIndex != -1){
            $("#actRouteSet .form-group").each(function () {
                var group = $(this);
                var json = {};
                var dex = 0;
                group.find("input").each(function () {
                    var input = $(this);
                    var name = input.attr("name");
                    var val = input.val();
                    json[name] = val;
                    dex++;
                });
                log(json);
                if(dex > 0){
                    jsonArr.push(json);
                }
            });
//            log(jsonArr);
//            log("设置:route_"+__lastIndex);
            __routeMap.put(__routeKeyPrefix+__lastIndex, JSON.stringify(jsonArr));
        }
        return jsonArr;
    }
</script>
<script src="/static/bflow/assets/js/bflow/processForm.js"></script>
</html>